/* ==========================    函数抽取 ================================*/
/**
 * @Describe: 验证手机号
 */
var checkPhoneNumber = function(num) {
    var mobile = num;
    var result = false;
    var msg = "";
    var phonetel = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
    if (mobile == '') {
        msg = "手机号不能为空!";
        uni.showToast({
            title: '手机号不能为空!',
            icon: "none"
        })
    } else if (mobile.length != 11) {
        msg = "手机号长度有误！";
        uni.showToast({
            title: '手机号长度有误！',
            icon: 'none',
        })
    } else if (!phonetel.test(mobile)) {
        msg = "手机号有误！";
        uni.showToast({
            title: '手机号有误！',
            icon: 'none',
        })
    } else {
        result = true;
    }
    if (!result) {
        uni.showToast({
            title: msg,
            icon: "none"
        })
    }
    return result;
}


/**
 * @Describe: 设置缓存同步
 *  get set remove clear
 */
var localStorageSyncServer = {
    /*
     * set 存储方法
     * @ param {String}     key 键
     * @ param {String}     value 值，
     * @ param {String}     expired 过期时间，以分钟为单位，非必须
     */
    set: function(key, value) {
        let curTime = new Date().getTime();
        uni.setStorageSync(key, { data: value, time: curTime })
    },
    get: function(key, expired = 2) {
        let dataObj = uni.getStorageSync(key)
        if (dataObj) {
            if (new Date().getTime() - dataObj.time > expired * 1000 * 60 * 60 * 24) {
                uni.removeStorageSync(key)
                var obj = ""
                return obj
            } else {
                return dataObj.data
            }
        }
    },
    remove: function(key) {
        uni.removeStorageSync(key)
    },
    clear: function() {
        uni.clearStorageSync()
    }
}

/**
 * @Describe: 秒 转化为时间
 */
function secondTransferTime(time) {
    if (time > 3600) {
        return [
                parseInt(time / 60 / 60),
                parseInt(time / 60 % 60),
                parseInt(time % 60)
            ]
            .join(":")
            .replace(/\b(\d)\b/g, "0$1");
    } else {
        return [
                parseInt(time / 60 % 60),
                parseInt(time % 60)
            ]
            .join(":")
            .replace(/\b(\d)\b/g, "0$1");
    }
}

/**
 * @Author : George
 * @Create : 2018/3/19
 * @Describe : 去除对象属性
 * @param   {Object,Array} material
 * @param   {Array,String} option
 * 增加递归属性recursion
 * */
function removeProperties(material, option) {
    this.run = function(aim) {
        if (option.constructor == Array) {
            for (var i = 0; i < option.length; i++) {
                var aimParam = option[i];
                if (aim.aimParam) {
                    delete aim.aimParam
                }
            }
        } else if (option.constructor == String) {
            if (aim[option]) {
                delete aim[option]
            }
        }
    };
    // 判断是否为material类型
    if (material.constructor != Object && material.constructor != Array) {
        return;
    }
    if (material.constructor == Array) {
        for (var j = 0; j < material.length; j++) {
            this.run(material[j])
        }
    } else {
        this.run(material)
    }
}

/**
 * @Author : George
 * @Create : 2018/11/13
 * @Describe : 对象冻结
 * @param   {Object} material
 * */
function freezeConstant(obj) {
    if (typeof obj !== 'object') {
        return obj
    }
    Object.freeze(obj);
    Object.keys(obj).forEach(key => {
        if (typeof obj[key] === 'object') {
            freezeConstant(obj[key])
        }
    });
    return obj;
}

/**
 * @Author : George
 * @Create : 2018/11/13
 * @Describe : 随机数
 * @param n
 * @param type  0 混合  1 数字 2 字母
 * */
function randomGenerator(n, type = 0) {
    var char1 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    var char2 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    var result = "",
        chars = char1.concat(char2);
    var range = 35;
    if (type == 1) {
        range = 9;
        chars = char1
    } else if (type == 2) {
        range = 25;
        chars = char2
    }
    for (var i = 0; i < n; i++) {
        var id = Math.ceil(Math.random() * range);
        result += chars[id];
    }
    return result;
}

/**
 * @Author : George
 * @Create : 2018/11/14
 * @Describe : 驼峰格式转换
 * @param parameter ， separator 分隔符
 * */
function camelCase(parameter, separator = "_") {
    if (typeof parameter === "object") {
        Object.keys(parameter).forEach(key => {
            let value = parameter[key];
            delete parameter[key];
            let convertKey = convert(key);
            parameter[convertKey] = value;
            if (typeof value === "object") {
                parameter[convertKey] = camelCase(value);
            }
        });
    } else if (typeof parameter === "string") {
        parameter = convert(parameter)
    }

    function convert(str) {
        let reg = new RegExp(separator + "([a-z0-9])", "gim");
        return str.replace(reg, function(all, letter) {
            return letter.toUpperCase();
        });
    }
    return parameter
}

/**
 * @Author : George
 * @Create : 2018/11/26
 * @Describe : 查看字符串字符长度
 * @param str
 * */
function bytesNumber(str) {
    if (typeof str === "string") {
        return str.replace(/[^\x00-\xff]/g, "zf").length
    } else {
        return str
    }
}

/**
 * @Author : George
 * @Create : 2018/12/10
 * @Describe : 小程序版本更新
 * */
function updateMiniProgram() {
    if (uni.canIUse('getUpdateManager')) {
        const updateManager = uni.getUpdateManager();
        updateManager.onCheckForUpdate(function(res) {
            if (res.hasUpdate) { // 请求完新版本信息的回调
                updateManager.onUpdateReady(function() {
                    uni.showModal({
                        title: '更新提示',
                        content: '新版本已经准备好，是否重启应用？',
                        success: function(res) {
                            if (res.confirm) {
                                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                                updateManager.applyUpdate()
                            }
                        }
                    })
                });
                updateManager.onUpdateFailed(function() {
                    // 新的版本下载失败
                    uni.showModal({
                        title: '已经有新版本了哟~',
                        content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
                    })
                })
            }
        })
    } else {
        // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
        uni.showModal({
            title: '提示',
            content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
        })
    }
}

function GetRequest(url) {
    let app = getApp()
    console.log(url)
    if (url.indexOf("?") != -1) {
        var str = url;
    } else {
        var str = url + "?userInfoId=" + app.globalData.userInfo.userInfoId
    }
    return str;
}
/**
 * @Author : George
 * @Create : 2018/12/10
 * @Describe :客户端判断
 * */
function getstemInfo() {
    switch (uni.getSystemInfoSync().platform) {
        case 'android':
            return {
                platform: 'app',
                stemInfo: 'android'
            }
            break;
        case 'ios':
            return {
                platform: 'app',
                stemInfo: 'ios'
            }
            break;
        default:
            return {
                platform: 'devtools',
                stemInfo: ''
            }
            break;
    }
}

export {
    checkPhoneNumber,
    localStorageSyncServer,
    secondTransferTime,
    removeProperties,
    freezeConstant,
    randomGenerator,
    camelCase,
    bytesNumber,
    updateMiniProgram,
    GetRequest,
    getstemInfo
}